package com.shuhe.timer;

import com.shuhe.JettyServer;
import com.shuhe.metastore.MetaMysql;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.TimerTask;

import static com.shuhe.common.CommonFunction.closeDb;

public class MyTaskBackKs extends TimerTask {
    private static boolean isRunning = false;
    private static Logger logger = Logger.getLogger(JettyServer.class);
    public static Properties globalProperties = new Properties();

    public MyTaskBackKs() {
    }

    public void run() {
        if (!isRunning) {
            if (true) {
                isRunning = true;
                System.out.println("开始库备份任务");
                MyTaskBackup();
                isRunning = false;
                System.out.println("库备份任务执行结束");
            }
        } else {
            System.out.println("上一次任务执行还未结束");
        }
    }

    public static void MyTaskBackup() {
        Connection metaConn = null;
        try {
            String sql = "select id,db_type,bat_list,backup_list  from  mxgc_backup_config order by id";
            String bat_list = "";
            String db_type = "";
            //读数据库，按照id排序
            metaConn = MetaMysql.connectByAll(JettyServer.globalProperties.getProperty("meta.url"),
                    JettyServer.globalProperties.getProperty("meta.user"),
                    JettyServer.globalProperties.getProperty("meta.password"),
                    JettyServer.globalProperties.getProperty("meta.driver"));
            ResultSet rs = MetaMysql.querySql(metaConn, sql);
            while (rs.next()) {
                bat_list = rs.getString("bat_list");
                db_type = rs.getString("db_type");
                logger.info("------------------" + db_type + "备份任务开始执行" + DateFormat.getDateTimeInstance().format(new Date()));
                Process process = Runtime.getRuntime().exec(bat_list);
                logger.info("------------------" + db_type + "备份任务结束执行" + DateFormat.getDateTimeInstance().format(new Date()));

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            closeDb(metaConn);
        }
    }

}

